<template>
	<view class="u-flex-1">
		<u-input
			:type="disabled ? 'input' : 'select'"
			v-model="options.label"
			:disabled="disabled"
			:placeholder="placeholder"
			:select-open="options.open"
			@click="inputClick"
		></u-input>
		<u-select
			:mode="options.mode"
			v-model="options.open"
			:list="options.items"
			:label-name="options.itemLabel"
			:value-name="options.itemValue"
			:default-value="options.currentIndex"
			@confirm="selectConfirm"
			style="width: 100%"
		></u-select>
	</view>
</template>
<script>
/**
 * 下拉选择组件
 * @property {Object} value 用于双向绑定选择框的值，返回选择框的 Value
 * @property {Boolean} disabled 是否禁用模式，是否只读模式
 * @property {String} tree 是否为树结构（默认 false）
 * @property {String} placeholder 选择框的占位符，提示文字
 * @property {String} dictType 字典类型，从字典里获取，自动设置 items、itemLabel、itemValue
 * @property {String} items 列表数据，可接受对象集合，如：[{name: '是', value: '否'}]
 * @property {String} itemLabel 指定列表数据中的什么属性名作为 option 的标签名，如 name
 * @property {String} itemValue 指定列表数据中的什么属性名作为 option 的 value 值，如 value
 * @example <js-select v-model="model.type" dict-type="sys_yes_no"></js-select>
 * @description Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * @author ThinkGem
 * @version 2021-3-11
 */
export default {
	props: {
		value: {
			type: null,
			default: ''
		},
		labelValue: {
			type: null,
			default: ''
		},
		placeholder: {
			type: String,
			default: '请选择选项'
		},
		disabled: {
			type: Boolean,
			default: false
		},
		userName: {
			type: String,
			default: ''
		},
		tree: {
			type: Boolean,
			default: false
		},
		dictType: {
			type: String,
			default: ''
		},
		multiple: {
			type: Boolean,
			default: false
		},
		items: {
			type: Array,
			default() {
				return [];
			}
		},
		itemLabel: {
			type: null,
			default: ''
		},
		itemValue: {
			type: null,
			default: ''
		},
		returnFullName: {
			type: Boolean,
			default: false
		},
		returnFullNameSplit: {
			type: String,
			default: '/'
		}
	},
	data() {
		return {
			num: 1,
			options: {
				value: this.value,
				label: this.labelValue,
				open: false,
				mode: 'single-column',
				items: this.items,
				itemLabel: this.itemLabel || 'name',
				itemValue: this.itemValue || (this.tree ? 'id' : 'value'),
				currentIndex: [],
				indexMap: {}
			}
		};
	},
	watch: {
		value(val, oldVal) {
			this.options.value = val;
			
			this.selectValue();
		},
		labelValue(val, oldVal) {
			this.options.label = val;
		},
		items(val, oldVal) {
		
			this.setItems(val);
		}
	},
	created() {
	
		this.loadData();
	},
	methods: {
		loadData() {

			if (this.dictType != '') {
				if (this.dictType == 'dc_task_type') {
					this.$u.api.taskInfo.getDict().then(res => {
						if (typeof res.data === 'object' && res.result === 'login') {
							return;
						}
						if (res.result == 'true') {
							var arr = [];
							res.data.forEach(item => {
								arr.push({
									id: item.id,
									name: item.dictLabel,
									pId: item.dictType,
									value: item.dictValue
								});
							});
							uni.setStorageSync('arr', arr);

							this.setItems(arr);
						} else {
							var arr1 = [];
							arr1 = uni.getStorageSync('arr');
							this.setItems(arr1);
						}
					});
				} else {
					this.$u.api.dictData({ dictType: this.dictType }).then(res => {
				
						if (typeof res === 'object' && res.result === 'login') {
							return;
						}

						this.setItems(res);
					});
				}

				// this.$u.api.dictData({ dictType: this.dictType }).then(res => {
				// 	console.log(res, 'res');
				// 	if (typeof res === 'object' && res.result === 'login') {
				// 		return;
				// 	}

				// 	this.setItems(res);
				// });
			} else {
				this.setItems(this.items);
			}
		},
		setItems(res) {
			if (this.tree) {
				this.options.mode = 'mutil-column-auto';
			
				res = this.convertTree(res);
				if (res && res.length > 0) {
					res.map(item => {
						if (item.children == undefined) {
							let children = [
								{
									name: '',
									id: '',
									pId: ''
								}
							];
							item.children = children;
						}
					});
				}
			}
			if (res && res.length > 0 && res != '') {
				this.options.items = res;
			}

			

			this.selectValue();
		},
		selectValue() {
			// console.log('xiala');
			if (!this.options.value) {
				return;
			}
			for (let i in this.options.items) {
				let item = this.options.items[i];
				this.options.indexMap[item[this.options.itemValue]] = Number(i);
				if (item[this.options.itemValue] == this.options.value) {
					// this.options.value = item[this.options.itemValue];
					this.options.label = item[this.options.itemLabel];
					if (!this.tree && this.options.indexMap[this.options.value]) {
						this.options.currentIndex = [this.options.indexMap[this.options.value]];
					}
				}
			}
		},
		convertTree(data) {
			
			let i,
				l,
				key = 'id',
				parentKey = 'pId',
				childKey = 'children';
			if (Object.prototype.toString.apply(data) === '[object Array]') {
				let treeData = [],
					map = [];
				for (i = 0, l = data.length; i < l; i++) {
					map[data[i][key]] = data[i];
				}
				for (i = 0, l = data.length; i < l; i++) {
					if (map[data[i][parentKey]] && data[i][key] != data[i][parentKey]) {
						if (!map[data[i][parentKey]][childKey]) {
							map[data[i][parentKey]][childKey] = [];
						}
						map[data[i][parentKey]][childKey].push(data[i]);
						
					} else {
						// console.log(data[i]);
						treeData.push(data[i]);
						
					}
				}
				this.num = 2;
				return treeData;
			} else {
				return [data];
			}
		},
		inputClick() {
			if (!this.disabled) {
				setTimeout((this.options.open = true), 1000);
			}
		},
		selectConfirm(items) {
		
			let values = [],
				labels = [],
				currentIndexes = [];
			for (let i in items) {
				let item = items[i];
				values.push(String(item.value).replace(/^u_/g, ''));
				labels.push(String(item.label));
				if (!this.tree && this.options.indexMap[item.value]) {
					currentIndexes.push(this.options.indexMap[item.value]);
				}
			}
			this.options.value = values.length > 0 ? values[values.length - 1] : '';
			if (this.returnFullName) {
				this.options.label = labels.join(this.returnFullNameSplit);
			} else {
				this.options.label = labels.length > 0 ? labels[labels.length - 1] : '';
			}
			if (!this.tree) {
				this.options.currentIndex = currentIndexes;
			}
			
			this.$emit('label-value', this.options.value);
			this.$emit('label-input', this.options.label);
			this.$emit('confirm', this.options.value, this.options.label);
		}
	}
};
</script>
<style lang="scss" scoped>
.shadow {
	width: 100%;
	height: 100%;
	background-color: blue($color: #aa5500);
}
</style>
